package com.pdstudio.carrecom.ui.activity.owner;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.fourmob.datetimepicker.date.DatePickerDialog;
import com.fourmob.datetimepicker.date.DatePickerDialog.OnDateSetListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.http.RequestParams;
import com.pdstudio.carrecom.R;
import com.pdstudio.carrecom.api.HttpExecuteJson;
import com.pdstudio.carrecom.api.HttpExecuteJson.httpReturnJson;
import com.pdstudio.carrecom.api.ServiceHelper;
import com.pdstudio.carrecom.app.AppContext;
import com.pdstudio.carrecom.bean.ResultInfo;
import com.pdstudio.carrecom.bean.owner.Render;
import com.pdstudio.carrecom.logger.Logger;
import com.pdstudio.carrecom.tools.StringUtils;
import com.pdstudio.carrecom.tools.UIHelper;
import com.pdstudio.carrecom.ui.activity.buy.ActivityNewCar;

/**
 * 
 * 类: ActivityWyzcOrder <br>
 * 描述: 我是车主——我要租车预约界面 <br>
 * 作者: ws <br>
 * 时间: 2015-6-15 下午11:32:03
 */
public class ActivityWyzcOrder extends FragmentActivity implements
		OnClickListener, OnDateSetListener {

	private static final String TAG = "ActivityWyzcOrder";
	public static final String DATEPICKER_TAG = "datepicker";

	private static final int MSG_WHAT_ABOUT = 1;

	private TextView txtTitle;
	private ImageView ivBack;

	private ResultInfo mResultInfo;

	private AppContext mAppContext = AppContext.getInstance();

	private LinearLayout mStartLayout;
	private LinearLayout mEndLayout;
	private DatePickerDialog datePickerDialog;
	private DatePickerDialog mEndDatePickerDialog;

	private TextView mStartTime;
	private TextView mEndTime;

	private EditText mContac;

	private Button mSubmit;

	private Render mRender;
	private EditText mPhone;
	private EditText mStartAddress;
	private EditText mDis;
	private EditText mDistance;
	private EditText mRemark;
	private String model = "";
	private String series = "";
	private String brand = "";
	private int rentalId;

	/** 刷新页码,从1开始 */
	private int mPageIndex = 1;
	/** 刷新数据条数 */
	private int mPageSize = 10;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_owner_wyzcorder);

		Intent i = getIntent();
		mRender = (Render) i.getSerializableExtra("WYZC_DETAIL");
		rentalId = mRender.id;
		series = mRender.series;
		brand = mRender.brand;

		initTitle();
		initView();

		final Calendar calendar = Calendar.getInstance();
		final Calendar endCalendar = Calendar.getInstance();
		datePickerDialog = DatePickerDialog.newInstance(this,
				calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DAY_OF_MONTH), true);

		mEndDatePickerDialog = DatePickerDialog.newInstance(this,
				endCalendar.get(Calendar.YEAR),
				endCalendar.get(Calendar.MONTH),
				endCalendar.get(Calendar.DAY_OF_MONTH), true);
	}

	@Override
	protected void onResume() {
		super.onResume();

		getBoutiques();
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Logger.i(TAG, msg);
			switch (msg.what) {
			case MSG_WHAT_ABOUT:// 关于

				break;

			default:
				break;
			}
		}
	};
	private TextView mBrand;
	private TextView mSeries;
	private TextView mModel;
	private Button mCall;

	/**
	 * 方法: initTitle <br>
	 * 描述: 初始化页面标题 <br>
	 * 作者: ws <br>
	 * 时间: 2015-5-24 下午5:46:11
	 */
	private void initTitle() {
		txtTitle = (TextView) findViewById(R.id.title_text_nav);

		txtTitle.setText("我要租车");

		ivBack = (ImageView) findViewById(R.id.title_back);
		ivBack.setOnClickListener(this);
	}

	private void initView() {
		mStartLayout = (LinearLayout) findViewById(R.id.wyzcorder_start);
		mStartLayout.setOnClickListener(this);

		mEndLayout = (LinearLayout) findViewById(R.id.wyzcorder_finish);
		mEndLayout.setOnClickListener(this);

		mStartTime = (TextView) findViewById(R.id.starttime);
		mEndTime = (TextView) findViewById(R.id.endtime);

		mContac = (EditText) findViewById(R.id.owner_bxxb_srpp);
		mPhone = (EditText) findViewById(R.id.owner_bxxb_series);
		mStartAddress = (EditText) findViewById(R.id.owner_bxxb_srkx);
		mDis = (EditText) findViewById(R.id.exchange_serial);
		mDistance = (EditText) findViewById(R.id.distance);
		mRemark = (EditText) findViewById(R.id.memo);

		mSubmit = (Button) findViewById(R.id.exchange_submit);
		mSubmit.setOnClickListener(this);
		
		mCall = (Button) findViewById(R.id.wyzcorder_call);
		mCall.setOnClickListener(this);

		mBrand = (TextView) findViewById(R.id.render_brand);
		mSeries = (TextView) findViewById(R.id.render_series);
		mModel = (TextView) findViewById(R.id.render_model);

		mBrand.setText(brand);
		mSeries.setText(series);
		mModel.setText(model);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_back:
			finish();
			break;
		case R.id.wyzcorder_start:

			datePickerDialog.setVibrate(true);
			datePickerDialog.setYearRange(1985, 2028);
			datePickerDialog.setCloseOnSingleTapDay(true);
			datePickerDialog.show(getSupportFragmentManager(), DATEPICKER_TAG);
			break;

		case R.id.wyzcorder_finish:
			mEndDatePickerDialog.setVibrate(true);
			mEndDatePickerDialog.setYearRange(1985, 2028);
			mEndDatePickerDialog.setCloseOnSingleTapDay(true);
			mEndDatePickerDialog.show(getSupportFragmentManager(),
					"DATEPICKER_TAG2");
			break;
		case R.id.exchange_submit:
			submit();
			break;
		case R.id.wyzcorder_call:
			//用intent启动拨打电话  
            Intent intent2 = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+mCall.getText().toString()));  
            startActivity(intent2);  
			break;
		}
	}

	private void submit() {
		try {
			HttpExecuteJson http = new HttpExecuteJson(this, mBuyOrderListener);
			RequestParams rps = new RequestParams();
			rps.addBodyParameter("uid", AppContext.getInstance().getUserId()
					+ "");
			rps.addBodyParameter("os", "android");
			rps.addBodyParameter("content",
					StringUtils.utf8Encode(mRemark.getText().toString()));
			rps.addBodyParameter("model", model);
			rps.addBodyParameter("series", series);
			rps.addBodyParameter("brand", brand);
			rps.addBodyParameter("rentalId", rentalId + "");
			rps.addBodyParameter("type", "4");
			rps.addBodyParameter("startAddress", mStartAddress.getText()
					.toString());
			rps.addBodyParameter("endAddress", mDis.getText().toString());
			rps.addBodyParameter("startDate", mStartTime.getText().toString());
			rps.addBodyParameter("endDate", mEndTime.getText().toString());
			rps.addBodyParameter("mil", mDistance.getText().toString());
			rps.addBodyParameter("name",
					StringUtils.utf8Encode(mContac.getText().toString()));
			rps.addBodyParameter("tel",
					StringUtils.utf8Encode(mPhone.getText().toString()));
			http.post(ServiceHelper.WYZCTJYY, rps);
		} catch (Exception e) {
		}

	}

	private httpReturnJson mBuyOrderListener = new httpReturnJson() {
		@Override
		public void onFailure(int error, String msg) {
			UIHelper.ToastMessage(ActivityWyzcOrder.this, "预约失败！" + msg);
		}

		@Override
		public void onCancel() {
			UIHelper.ToastMessage(ActivityWyzcOrder.this, "预约失败！");
		}

		// 获取到饲料配方类型成功
		public void onSuccess(String result) {
			DoJsonSub(result);
		}
	};

	/*
	 * 提交预约
	 */
	private void DoJsonSub(String json) {
		ResultInfo edv = null;
		try {
			edv = new Gson().fromJson(json, new TypeToken<ResultInfo>() {
			}.getType());
			if ((edv != null)
					&& (edv.msg.equals(ServiceHelper.msg_code_sucess))) {
				UIHelper.ToastMessage(ActivityWyzcOrder.this, "预约成功！");
				finish();
			} else {
				UIHelper.ToastMessage(ActivityWyzcOrder.this, "预约失败！" + edv.msg);

			}
		} catch (Exception e) {
			e.printStackTrace();
			UIHelper.ToastMessage(ActivityWyzcOrder.this,
					"预约失败！" + e.getMessage());
		}
	}

	/**
	 * 
	 * 方法: getBoutiques <br>
	 * 描述: 获取我要租车列表 <br>
	 * 作者: ws <br>
	 * 时间: 2015-6-16 上午12:27:40
	 */
	private void getBoutiques() {
		try {
			HttpExecuteJson http = new HttpExecuteJson(this,
					mNewCarBoutiqueListener);
			String url = ServiceHelper.OwnerWyzc;
			Map<String, Object> rps = new HashMap<String, Object>();
			rps.put("os", "android");
			rps.put("size", "30-60");
			rps.put("start", ((mPageIndex - 1) * mPageSize) + 1);
			rps.put("end", mPageIndex * mPageSize);
			rps.put("uid", mAppContext.getUserId());
			Logger.i(url);
			http.get(url, rps);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private httpReturnJson mNewCarBoutiqueListener = new httpReturnJson() {

		@Override
		public void onSuccess(String result) {
			Logger.json(result);
			ResultInfo resultInfo = null;
			try {
				resultInfo = new Gson().fromJson(result,
						new TypeToken<ResultInfo>() {
						}.getType());
				if ((resultInfo != null)
						&& (resultInfo.msg
								.equals(ServiceHelper.msg_code_sucess))) {
					try {
						mResultInfo = resultInfo;

						// mNews = JsonUtil.fromJsonArray(
						// JsonUtil.toJson(mResultInfo.data),
						// Render.class);
						Message msg = new Message();
						// msg.obj = mNews;
						msg.what = MSG_WHAT_ABOUT;
						mHandler.sendMessage(msg);

					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {

				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		@Override
		public void onFailure(int error, String msg) {

		}

		@Override
		public void onCancel() {

		}
	};

	@Override
	public void onDateSet(DatePickerDialog datePickerDialog, int year,
			int month, int day) {

		switch (datePickerDialog.getTag()) {
		case "DATEPICKER_TAG2":
			String endTimeString = year + "-" + (month + 1) + "-" + day;
			mEndTime.setText(endTimeString);

			break;
		case DATEPICKER_TAG:
			String startTimeString = year + "-" + (month + 1) + "-" + day;
			mStartTime.setText(startTimeString);
			break;
		default:
			break;
		}

	}

}
